package com.mogujie.tt.ui.adapter;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.R;
import com.mogujie.tt.ui.helper.Emoparser;
import com.mogujie.tt.ui.widget.QuanzQzReply;
import com.mogujie.tt.utils.GETUtil;

import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.List;

/**
 * Created by 50281 on 2015/9/17.
 */
public class QuanzQzReplyAdapter extends BaseAdapter implements OnClickListener {

    private Context context;

    private List<QuanzQzReply> list;
    private QuanzQzReply reply;
    private PopupWindow editWindow;
    private int pos;
    private TextView sendBtn;
    private EditText replyEdit;
    private View emo_layout_publish;
    private ImageView reply_emo_btn;

    private FlushListView1 flush;
    private FlushListView1 flush1;
    private int adap=0;

    public QuanzQzReplyAdapter(Context context,int pos,PopupWindow editwindow,final FlushListView1 flush) {
        this.context = context;
        this.pos = pos;
        this.flush = flush;
        this.editWindow = editwindow;
    }

    public QuanzQzReplyAdapter(Context context,final FlushListView1 flush1){
        this.context = context;
        this.flush1 = flush1;
        adap = 9;
    }
    public void setData(List<QuanzQzReply> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list == null ? null : list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.quanz_qz_reply_item, null);
            holder = getViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (list != null) {
            reply = list.get(position);
            reply.position=position;
            bindData(holder);
        }
        return convertView;
    }

    /**
     * 绑定数据
     *
     * @param holder
     */
    private void bindData(ViewHolder holder) {

        if (reply == null)
            return;
        System.out.println("444444=" + reply.friendId);
        holder.sendName.setText(reply.sendName);
        holder.replyName.setText(reply.replyName);
       // holder.content.setText(reply.content);
        holder.content.setText(Emoparser.getInstance(context).emoCharsequence(reply.content));
        if (isEmpty(reply.replyName)) {
            holder.replyName.setVisibility(View.GONE);
        } else {
            holder.replyName.setVisibility(View.VISIBLE);
        }
        if (isEmpty(reply.replyName)) {
            holder.replyTemp.setVisibility(View.GONE);
        } else {
            holder.replyTemp.setVisibility(View.VISIBLE);
        }
        holder.content.setTag(reply);
    }

    /**
     * 初始化viewHolder
     *
     * @param convertView
     * @return
     */
    private ViewHolder getViewHolder(View convertView) {
        ViewHolder holder = new ViewHolder();
        holder.replyName = (TextView) convertView.findViewById(R.id.reply_name);
        holder.sendName = (TextView) convertView.findViewById(R.id.send_name);
        holder.content = (TextView) convertView.findViewById(R.id.content);
        holder.replyTemp = (TextView) convertView.findViewById(R.id.reply_temp);
        holder.sendName.setOnClickListener(this);
        holder.replyName.setOnClickListener(this);
        holder.content.setOnClickListener(this);
        return holder;
    }

    private class ViewHolder {
        public TextView replyName;// 回复的名字
        public TextView sendName;// 发送的名字
        public TextView content;// 回复的内容
        public TextView replyTemp;// 回复文字
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.send_name:
                Toast.makeText(context, "去到他的首页", Toast.LENGTH_SHORT).show();
                break;
            case R.id.reply_name:
                Toast.makeText(context, "去到他的首页", Toast.LENGTH_SHORT).show();
                break;
            case R.id.content:
                reply = (QuanzQzReply) v.getTag();
                if (adap==9){
                    flush1.flush(reply.getPosition(),String.valueOf(reply.friendId),reply.userId,String.valueOf(reply.f_friendId),reply.sendName,v);
                    return;
                }
                replyEdit = (EditText) editWindow.getContentView().findViewById(
                        R.id.reply);
                sendBtn = (TextView) editWindow.getContentView().findViewById(
                        R.id.send_reply);
                emo_layout_publish = editWindow.getContentView().findViewById(R.id.emo_layout_publish);
                emo_layout_publish.setVisibility(View.GONE);
                reply_emo_btn = (ImageView) editWindow.getContentView().findViewById(R.id.reply_emo_btn);
                reply_emo_btn.setOnClickListener(this);
                reply_emo_btn.setTag(v.getTag());
                sendBtn.setOnClickListener(this);
                sendBtn.setTag(v.getTag());
                flush.flush(pos,String.valueOf(reply.friendId),reply.userId,String.valueOf(reply.f_friendId),reply.sendName,v);
                System.out.println("444444" + reply.f_friendId+"    "+reply.userId);
                break;
            case R.id.send_reply:
                emo_layout_publish.setVisibility(View.GONE);
                reply = (QuanzQzReply) v.getTag();
                final String o_edit = "回复@"+reply.sendName+"："+replyEdit.getText().toString();
                final String vo_feed_id = String.valueOf(reply.f_friendId);
                final String o_replyName = reply.sendName;
                if (TextUtils.isEmpty(replyEdit.getText().toString())){
                    Toast.makeText(context,"请输入。。。",Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.i("sxun", "send btn is click" + replyEdit.getText().toString());
                new AsyncTask<String, Void, Object>() {
                    protected void onPostExecute(Object result) {
                        super.onPostExecute(result);
                        try {
                            JSONObject status = new JSONObject(result.toString());
                            System.out.println("4444444455566="+status);
                            if (status.getString("status").equals("1")){
                                JSONObject data = status.getJSONObject("data");
                                JSONObject result1 = data.getJSONObject("result");
                                JSONObject user_info = result1.getJSONObject("user_info");
                                QuanzQzReply reply  = new QuanzQzReply();
                                reply.content = replyEdit.getText().toString();
                                reply.replyName = o_replyName;
                                reply.userId = user_info.getString("uid");
                                reply.friendId = Integer.valueOf(result1.getString("comment_id"));//就是在回复数据库中的id  ***
                                reply.id = Integer.valueOf(result1.getString("row_id"));
                                reply.sendName = user_info.getString("nick");
                                reply.f_friendId = Integer.valueOf(vo_feed_id);
                                list.add(0, reply);
                                replyEdit.setText("");
                                editWindow.dismiss();
                                System.out.println("7788888");
                                flush.flushmesshage(v);
                                //quanzQzReplyAdapter.notifyDataSetChanged();
                            }else if (status.getString("status").equals("0")){
                                Toast.makeText(context,"评论失败",Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                    }
                    protected Object doInBackground(String... params) {

                        String result = null;
                        try {
                            result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText1("public", "Index", "addcomment",
                                    LoginSp.instance().getLoginIdentity().getLoginName(), LoginSp.instance().getLoginIdentity().getPwd(), "public", "feed",
                                    String.valueOf(LoginSp.instance().getLoginIdentity().getLoginId()),vo_feed_id, String.valueOf(reply.friendId), reply.userId, URLEncoder.encode(o_edit, "GBK")));
                            return result;
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                        return "";
                    }
                }.execute();
                break;
            case R.id.reply_emo_btn:
                flush.flushmesshage(v);
                break;
            default:
                break;
        }
    }


    /**
     * 判断指定的字符串是否是 正确的（不为“”、null 、“null”）
     *
     * @param str
     * @return
     */
    private boolean isEmpty(String str) {
        if (str != null && !"".equals(str) && !"null".equals(str))
            return false;
        return true;
    }
    public interface FlushListView1 {
        public void flush(int pos, String feed_id, String to_uid, String f_feed_id, String sendName, View v);
        public void flushmesshage(View v);
        public void flushdetails();
    }
}
